﻿using Newtonsoft.Json;
using Senparc.Weixin.Context;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.Containers;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.Entities.Request;
using Senparc.Weixin.MP.MessageHandlers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;

namespace ZBJF.Warranty.WeiXin
{
    /// <summary>
    /// 消息事件处理
    /// </summary>
    public class CustomMessageHandler : MessageHandler<MessageContext<IRequestMessageBase, IResponseMessageBase>>
    {

        private string appId = "";
        private string appSecret = "";
        private string serviceSiteUrl = "";
        /// <summary>
        /// 模板消息集合（Key：checkCode，Value：OpenId）
        /// </summary>
        public static Dictionary<string, string> TemplateMessageCollection = new Dictionary<string, string>();

        public CustomMessageHandler(Stream inputStream, PostModel postModel, int maxRecordCount = 0)
            : base(inputStream, postModel, maxRecordCount)
        {
            WeixinContext.ExpireMinutes = 3;

            if (!string.IsNullOrEmpty(postModel.AppId))
            {
                appId = postModel.AppId;
            }
            this.appSecret = WeiXinConfig.APPSECRET;
            this.serviceSiteUrl = WeiXinConfig.ServiceSiteUrl;
            //在指定条件下，不使用消息去重
            base.OmitRepeatedMessageFunc = requestMessage =>
            {
                var textRequestMessage = requestMessage as RequestMessageText;
                if (textRequestMessage != null && textRequestMessage.Content == "容错")
                {
                    return false;
                }
                return true;
            };
        }

        public CustomMessageHandler(RequestMessageBase requestMessage)
            : base(requestMessage)
        {
        }
        public override void OnExecuting()
        {
            //测试MessageContext.StorageData
            if (CurrentMessageContext.StorageData == null)
            {
                CurrentMessageContext.StorageData = 0;
            }
            base.OnExecuting();
        }

        public override void OnExecuted()
        {
            base.OnExecuted();
            CurrentMessageContext.StorageData = ((int)CurrentMessageContext.StorageData) + 1;
        }

        #region 消息

        #region 默认处理（所有没有被处理的消息会默认返回这里的结果）+ IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage)
        /// <summary>
        /// 默认处理（所有没有被处理的消息会默认返回这里的结果）
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage)
        {
            var responseMessage = this.CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "不能处理的消息";
            return responseMessage;
        }
        #endregion

        #region 文本消息 + IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        /// <summary>
        /// 文本消息
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            //WebUtils web = new WebUtils();
            //string url = serviceSiteUrl + "/api/SocketApi/CustomerMassage";
            //Dictionary<string, string> param = new Dictionary<string, string>();
            //param.Add("OpenId", requestMessage.FromUserName);
            //param.Add("Time", requestMessage.CreateTime.ToString());
            //param.Add("MessageType", "100");
            //param.Add("Message", requestMessage.Content);
            //string result = web.DoPost(url, param);
            //LogHelper.WriteLog("客户发送文本消息给客服：" + JsonConvert.SerializeObject(requestMessage) + "；H5返回消息：" + result, LogType.remark);

            //var responseMessage = this.CreateResponseMessage<ResponseMessageText>();
            //responseMessage.Content = null;
            return new SuccessResponseMessage();
        }
        #endregion

        #region 图片消息 + IResponseMessageBase OnImageRequest(RequestMessageImage requestMessage)
        /// <summary>
        /// 图片消息
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnImageRequest(RequestMessageImage requestMessage)
        {
            //WebUtils web = new WebUtils();
            //string url = serviceSiteUrl + "/api/SocketApi/CustomerMassage";
            //Dictionary<string, string> param = new Dictionary<string, string>();
            //param.Add("OpenId", requestMessage.FromUserName);
            //param.Add("Time", requestMessage.CreateTime.ToString());
            //param.Add("MessageType", "200");
            //param.Add("Message", requestMessage.PicUrl);
            //string result = web.DoPost(url, param);
            //LogHelper.WriteLog("客户发送图片消息给客服："+ JsonConvert.SerializeObject(requestMessage)+"；H5返回消息："+ result, LogType.remark);
            return new SuccessResponseMessage();
        }
        #endregion

        #region 语音消息
        /// <summary>
        /// 图片消息
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnVoiceRequest(RequestMessageVoice requestMessage)
        {
            //WebUtils web = new WebUtils();
            //string url = serviceSiteUrl + "/api/SocketApi/CustomerMassage";
            //Dictionary<string, string> param = new Dictionary<string, string>();
            //param.Add("OpenId", requestMessage.FromUserName);
            //param.Add("Time", requestMessage.CreateTime.ToString());
            //param.Add("MessageType", "300");
            //param.Add("Message", requestMessage.MediaId);
            //param.Add("FileType", requestMessage.Format);
            //string result = web.DoPost(url, param);
            //LogHelper.WriteLog("客户发送语音消息给客服：" + JsonConvert.SerializeObject(requestMessage) + "；H5返回消息：" + result, LogType.remark);
            return new SuccessResponseMessage();
        }
        #endregion

        #endregion

        #region 事件

        #region  订阅（关注）事件 + IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        /// <summary>
        /// 订阅（关注）事件
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        {
            var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
            responseMessage.Content = "";

            //微信扫码关注的Url参数
            string urlParams = requestMessage.EventKey;
            if (!string.IsNullOrEmpty(urlParams))
            {
                //===============================================业务逻辑
            }
            LogHelper.WriteLog("订阅（关注）事件：" + JsonConvert.SerializeObject(requestMessage) + "\r\n 响应消息：" + JsonConvert.SerializeObject(responseMessage), LogType.remark);
            return responseMessage;
        }
        #endregion

        #region 取消关注事件 + IResponseMessageBase OnEvent_UnsubscribeRequest(RequestMessageEvent_Unsubscribe requestMessage)
        /// <summary>
        /// 取消关注事件
        /// 实际上用户无法收到非订阅账号的消息，所以这里可以随便写。
        /// unsubscribe事件的意义在于及时删除网站应用中已经记录的OpenID绑定，消除冗余数据。并且关注用户流失的情况。
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_UnsubscribeRequest(RequestMessageEvent_Unsubscribe requestMessage)
        {

            var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "您取消了关注。";

            LogHelper.WriteLog("取消关注事件：" + JsonConvert.SerializeObject(requestMessage) + "\r\n 响应消息：" + JsonConvert.SerializeObject(responseMessage), LogType.remark);
            return responseMessage;
        }
        #endregion

        #region 扫描带参数二维码事件 + IResponseMessageBase OnEvent_ScanRequest(RequestMessageEvent_Scan requestMessage)
        /// <summary>
        /// 扫描带参数二维码事件
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_ScanRequest(RequestMessageEvent_Scan requestMessage)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "";
            LogHelper.WriteLog("扫描带参数二维码事件：" + JsonConvert.SerializeObject(requestMessage) + "\r\n 响应消息：" + JsonConvert.SerializeObject(responseMessage), LogType.remark);
            return responseMessage;
        }
        #endregion

        #region 点击菜单跳转链接时的事件推送 + IResponseMessageBase OnEvent_ViewRequest(RequestMessageEvent_View requestMessage)
        /// <summary>
        /// 点击菜单跳转链接时的事件推送
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_ViewRequest(RequestMessageEvent_View requestMessage)
        {
            //说明：这条消息只作为接收，下面的responseMessage到达不了客户端，类似OnEvent_UnsubscribeRequest
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "";
            LogHelper.WriteLog("点击菜单跳转链接时的事件推送：" + JsonConvert.SerializeObject(requestMessage) + "\r\n 响应消息：" + JsonConvert.SerializeObject(responseMessage), LogType.remark);
            return responseMessage;
        }
        #endregion

        #region 点击按钮事件 +  IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        /// <summary>
        /// 点击按钮事件
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            LogHelper.WriteLog("点击按钮事件推送：" + JsonConvert.SerializeObject(requestMessage) + ";", LogType.tag);
            var responseMessageText = base.CreateResponseMessage<ResponseMessageText>();
            switch (requestMessage.EventKey)
            {
                //手机维修
                case "zbjf_MobilePhoneRepair":
                    ////发送一条消息给用户
                    //string sendContent = "亲，感谢您的咨询，如您需要使用碎屏险报案服务，请按照您保单上的信息，将被“保险人姓名、电话以及您购买碎屏险的渠道”在下方消息框直接发送给我们，我们的客服将在工作时间内将会第一时间给您回复~";
                    //string accesstoken = AccessTokenContainer.TryGetAccessToken(appId, appSecret);
                    //CustomApi.SendText(accesstoken, requestMessage.FromUserName, sendContent);

                    //var responseMessageService = base.CreateResponseMessage<ResponseMessageTransfer_Customer_Service>();
                    //return responseMessageService;

                    responseMessageText.Content = "您好，如果您需要手机碎屏险维修服务，请按照您的保单信息，发送“姓名+电话+购买渠道”在下方的消息框中直接发送给我们，我们会第一时间回复您哦！";
                    return responseMessageText;
                    //家电维修
                case "zbjf_HomeApplianceRepair":
                    responseMessageText.Content = "您好，如果您需要家电维修服务，请按照您的保单信息，发送“姓名+电话+购买渠道”在下方的消息框中直接发送给我们，我们会第一时间回复您哦！";
                    return responseMessageText;
                    //家电清洗
                case "zbjf_HomeApplianceCleaning":
                    responseMessageText.Content = "您好，如果您需要家电清洗服务，请按照您的保单信息，发送“姓名+电话+购买渠道”在下方的消息框中直接发送给我们，我们会第一时间回复您哦！";
                    return responseMessageText;
                    //法律服务
                case "zbjf_LegalService":
                    responseMessageText.Content = "您好，如果您需要法律服务，请您拨打我们的法律服务热线400—8653—660，我们将有专业的法律工作人员为您服务！";
                    return responseMessageText;
                    //关于我们
                case "zbjf_AboutUs":
                    string accesstoken = AccessTokenContainer.TryGetAccessToken(appId, appSecret);
                    //CustomApi.SendText(accesstoken, requestMessage.FromUserName, sendContent);
                    CustomApi.SendMpNews(accesstoken, requestMessage.FromUserName, "RfN_2P36XPlqXf_Q7_cJDXVss9zSDNHKsQvv3PWIp5s");


                    var responseMessageNews = base.CreateResponseMessage<ResponseMessageNoResponse>();
                    return responseMessageNews; 
                default:
                    var responseMessageDefault = base.CreateResponseMessage<ResponseMessageText>();
                    responseMessageDefault.Content = "";
                    return responseMessageDefault;
            }
        }

        #endregion

        #endregion
    }
}
